package com.lly.tboc.zhouyi

import android.app.Application
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import com.lly.tboc.R
import com.lly.tboc.zhouyi.db.GuaDao
import com.lly.tboc.zhouyi.db.YaoDao
import com.lly.tboc.zhouyi.vo.Gua
import com.lly.tboc.zhouyi.vo.Yao
import com.lly.tboc.zhouyi.vo.YaoName
import com.lly.ui.GuaView
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GuaEditScreen(
    guaId: Int,
    navController: NavController,
    viewModel: EditGuaViewModel = hiltViewModel()
) {
    if (guaId != 0 && viewModel.id.value == 0) {
        viewModel.id.value = guaId
        viewModel.fill(guaId, false)
    }
    LaunchedEffect(key1 = viewModel) {
        viewModel.deleteState.collectLatest {
            if (it is ExectionResult.Success) {
                navController.popBackStack()
            }
        }
    }
    LaunchedEffect(key1 = viewModel) {
        viewModel.saveState.collectLatest {
            if (it is ExectionResult.Success) {
                navController.popBackStack()
            }
        }
    }
    LaunchedEffect(key1 = viewModel) {
        viewModel.insertState.collectLatest {
            when (it) {
                is ExectionResult.Success -> {
                    navController.popBackStack()
                    viewModel.insertState.value = ExectionResult.Idel()
                }

                is ExectionResult.Failed -> {
                    Toast.makeText(viewModel.context, it.msg, Toast.LENGTH_SHORT).show()
                    viewModel.insertState.value = ExectionResult.Idel()
                }

                is ExectionResult.Idel -> {}
            }
        }
    }
    Surface(color = MaterialTheme.colorScheme.primary) {
        val scrollBehavior =
            TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState())
        Scaffold(
            modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
            bottomBar = {
                bottomBar(viewModel)
            },
            containerColor = Color.Transparent,
            topBar = {
                CenterAlignedTopAppBar(
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer,
                        titleContentColor = MaterialTheme.colorScheme.primary,
                    ),
                    title = {
                        Text(
                            text = stringResource(id = R.string.zhouyi),
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    },
                    navigationIcon = {
                        IconButton(onClick = { navController.popBackStack() }) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = "Localized description"
                            )
                        }
                    },
                    scrollBehavior = scrollBehavior,
                )

            }
        ) {

            body(viewModel, Modifier.padding(it))
        }
    }
}

@Composable
private fun body(viewModel: EditGuaViewModel, modifier: Modifier) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.spacedBy(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        appContent(
            viewModel.id.collectAsStateWithLifecycle(),
            viewModel.name.collectAsStateWithLifecycle(),
            viewModel.outer.collectAsStateWithLifecycle(),
            viewModel.inner.collectAsStateWithLifecycle(),
            viewModel.ci.collectAsStateWithLifecycle(),
            viewModel.tuan.collectAsStateWithLifecycle(),
            viewModel.xiang.collectAsStateWithLifecycle(),
            viewModel.wu.collectAsStateWithLifecycle(),
            {
                viewModel.id.value = it.toIntOrNull() ?: 0
                viewModel.fill(viewModel.id.value)
            },
            {
                viewModel.name.value = it
                viewModel.fill(it)
            },
            {
                viewModel.outer.value = it
                viewModel.fillYaoInfo()
            },
            {
                viewModel.inner.value = it
                viewModel.fillYaoInfo()
            },
            { viewModel.ci.value = it },
            { viewModel.tuan.value = it },
            { viewModel.xiang.value = it },
            { viewModel.wu.value = it },
            viewModel.yaoes.collectAsState()
        ) {
            viewModel.updateYao(it)
        }
    }
}

@Composable
private fun bottomBar(viewModel: EditGuaViewModel) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceEvenly,
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
    ) {
        val openAlertDialog = remember { mutableStateOf(false) }

        if (!viewModel.existState.value) {
            Button(onClick = {
                viewModel.insert()
            }) {
                Text(text = stringResource(R.string.save))
            }
        } else {
            Button(onClick = {
                viewModel.update()
            }) {
                Text(text = stringResource(R.string.update))
            }
        }
        Button(onClick = {
            openAlertDialog.value = true
        }) {
            Text(text = stringResource(R.string.delete))
        }
        Button(onClick = {
            isExpandGuaInfoState.value = !isExpandGuaInfoState.value
        }) {
            Text(text = if (isExpandGuaInfoState.value) "折叠卦信息" else "展开卦信息")
        }
        if (openAlertDialog.value) {
            AlertDialog(
                onDismissRequest = { openAlertDialog.value = false },
                confirmButton = {
                    Text(text = stringResource(R.string.ok), modifier = Modifier.clickable {
                        viewModel.delete()
                        openAlertDialog.value = false
                    })
                },
                dismissButton = {
                    Text(text = stringResource(R.string.cancel), modifier = Modifier.clickable {
                        openAlertDialog.value = false
                    })
                },
                title = {
                    Text(
                        text = stringResource(R.string.delete)
                    )
                }, text = {
                    Text(
                        text = viewModel.getTarget().toDataForString(),
                        modifier = Modifier.clickable {
                            openAlertDialog.value = false
                        }
                    )
                }
            )

        }
    }
}

val isExpandGuaInfoState = mutableStateOf(true)

@Composable
private fun appContent(
    id: State<Int>,
    name: State<String>,
    outer: State<String>,
    inner: State<String>,
    ci: State<String>,
    tuan: State<String>,
    xiang: State<String>,
    wu: State<String>,
    onIdChanged: (String) -> Unit,
    onNameChanged: (String) -> Unit,
    onOuterChanged: (String) -> Unit,
    onInnerChanged: (String) -> Unit,
    onCiChanged: (String) -> Unit,
    onTuanChanged: (String) -> Unit,
    onXiangChanged: (String) -> Unit,
    onWuChanged: (String) -> Unit,
    yaoesState: State<Array<Yao>>,
    onYaoChanged: (Yao) -> Unit,
) {
    Column(
        verticalArrangement = Arrangement.spacedBy(16.dp),
        modifier = Modifier.padding(8.dp)
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            TextField(
                label = { Text(text = "卦序") },
                value = if (id.value == 0) "" else id.value.toString(),
                onValueChange = onIdChanged,
                modifier = Modifier.width(100.dp)
            )
            Spacer(modifier = Modifier.size(8.dp))

            TextField(
                label = { Text(text = "卦名") },
                value = name.value, onValueChange = onNameChanged,
                modifier = Modifier.width(100.dp)

            )
            Spacer(modifier = Modifier.size(8.dp))
            Column {
                selectGua(outer, onOuterChanged)
                Spacer(modifier = Modifier.size(8.dp))
                selectGua(inner, onInnerChanged)
            }
        }

        if (isExpandGuaInfoState.value) {
            TextField(
                label = { Text(text = "卦辞") },
                value = ci.value, onValueChange = onCiChanged
            )
            TextField(
                label = { Text(text = "彖辞") },
                value = tuan.value, onValueChange = onTuanChanged
            )
            TextField(
                label = { Text(text = "象辞") },
                value = xiang.value, onValueChange = onXiangChanged
            )
            TextField(
                label = { Text(text = "感悟") },
                value = wu.value, onValueChange = onWuChanged
            )
        }
        yaoesState.value.forEach { initYao ->
            Card {
                var yao by remember {
                    mutableStateOf(initYao)
                }
                var isExpand by remember {
                    mutableStateOf(true)
                }

                if (isExpand) {
                    TextField(label = {
                        Text(text = yao.id.toString())
                    }, value = yao.name, onValueChange = {
                        yao = yao.copy(name = it)
                    })
                    TextField(
                        label = { Text(text = "卦辞") },
                        value = yao.ci, onValueChange = {
                            yao = yao.copy(ci = it)

                        })
                    TextField(
                        label = { Text(text = "象辞") },
                        value = yao.xiang ?: "", onValueChange = {
                            yao = yao.copy(xiang = it)
                        })
                    TextField(
                        label = { Text(text = "感悟") },
                        value = yao.wu ?: "", onValueChange = {
                            yao = yao.copy(wu = it)

                        })
                    Button(onClick = {
                        onYaoChanged(yao)
                        isExpand = false
                    }) {
                        Text(
                            text = stringResource(id = R.string.update)
                        )
                    }
                }
                Button(onClick = { isExpand = !isExpand }) {
                    Text(text = if (isExpand) "折叠" else "展开")
                }


            }
        }
    }
}

@Composable
private fun selectGua(
    info: State<String>,
    onChanged: (String) -> Unit
) {
    val isClick = rememberSaveable { mutableStateOf(false) }
    val modifier = Modifier
        .height(20.dp)
        .width(20.dp)
    Surface(
        onClick = { isClick.value = !isClick.value },
        color = Color.Transparent,
        modifier = modifier
    ) {
        val yaoColor = LocalContentColor.current
        GuaView(
            yaoes = remember(info.value) {
                val ans = mutableListOf<YaoName>()
                Yao.yaoNames(info.value, ans)
                ans.map { it.toUiYao() }
            },
            selectedColor = yaoColor,
            color = yaoColor,
            modifier = modifier
        )

    }
    DropdownMenu(expanded = isClick.value, onDismissRequest = { }) {
        Gua.names.forEach {
            DropdownMenuItem(
                onClick = {
                    isClick.value = !isClick.value
                    onChanged(it)
                },
                text = { Text(text = it) }
            )
        }
    }
}

sealed class ExectionResult() {
    class Idel : ExectionResult()
    class Success : ExectionResult()
    class Failed(val msg: String) : ExectionResult()
}

@HiltViewModel
class EditGuaViewModel @Inject constructor(
    val context: Application,
    val guaDao: GuaDao,
    val yaoDao: YaoDao,
) : ViewModel() {
    var yaoes = MutableStateFlow<Array<Yao>>(emptyArray())

    val existState = MutableStateFlow(false)
    fun insert() {
        val target = getTarget()
        viewModelScope.launch(Dispatchers.Default) {
            if (guaDao.get(target.id) == null) {
                guaDao.insert(target)
                insertState.emit(ExectionResult.Success())
            } else {
                insertState.emit(ExectionResult.Failed(context.getString(R.string.insert_failed_hint)))

            }

        }
    }

    fun getTarget() = Gua(
        id.value, name.value, outer.value, inner.value,
        ci.value, xiang.value, tuan.value, wu.value
    )

    private var fillJobById: Job? = null
    fun fill(id: Int, needDelay: Boolean = true) {
        fillJobById?.cancel()
        fillJobById = viewModelScope.launch(Dispatchers.Default) {
            if (needDelay) {
                delay(2000)
            }
            val a = guaDao.get(id)
            existState.value = a != null
            a?.let {
//                withContext(Dispatchers.Main) {
                fill(it)
//                }
            }
            fillYaoInfo()
        }

    }

    fun fillYaoInfo() {
        val guaId = id.value
        val outerGua = outer.value
        val innerGua = inner.value
        if (guaId > 0 && outerGua.isNotEmpty() && innerGua.isNotEmpty()) {
            viewModelScope.launch(Dispatchers.Default) {
                val datas = Yao.generate(guaId, outerGua, innerGua)
                yaoDao.get(guaId).filter { it.id < datas.size }.forEach {
                    datas[it.id] = it
                }
                yaoes.emit(datas)
            }
        }
    }

    fun fill(name: String) {
        viewModelScope.launch(Dispatchers.Default) {
            guaDao.get(name)?.let {
                withContext(Dispatchers.Main) {
                    fill(it)
                }
            }
        }

    }

    private fun fill(it: Gua) {
        if (id.value == 0) {
            id.value = it.id
        }
        if (name.value.isEmpty()) {
            name.value = it.name
        }
        if (outer.value.isEmpty()) {
            outer.value = it.outer
        }
        if (inner.value.isEmpty()) {
            inner.value = it.inner
        }
        if (ci.value.isEmpty()) {
            ci.value = it.ci
        }
        if (tuan.value.isEmpty()) {
            tuan.value = it.tuan ?: ""
        }
        if (xiang.value.isEmpty()) {
            xiang.value = it.xiang ?: ""
        }
        if (wu.value.isEmpty()) {
            wu.value = it.wu ?: ""
        }
    }

    fun update() {
        val target = getTarget()
        viewModelScope.launch(Dispatchers.Default) {
            guaDao.insert(target)
            saveState.emit(ExectionResult.Success())
        }
    }

    fun delete() {
        val target = getTarget()
        viewModelScope.launch(Dispatchers.Default) {
            guaDao.delete(target)
            deleteState.value = (ExectionResult.Success())
        }
    }

    fun updateYao(yao: Yao) {
        val datas = yaoes.value
        if (datas.size >= yao.id) {
            datas[yao.id] = yao
            viewModelScope.launch(Dispatchers.Default) {
                yaoDao.insert(yao)
            }
        }
    }

    val insertState = MutableStateFlow<ExectionResult>(ExectionResult.Idel())
    val saveState = MutableStateFlow<ExectionResult>(ExectionResult.Idel())
    val deleteState = MutableStateFlow<ExectionResult>(ExectionResult.Idel())
    var id = MutableStateFlow(0)
    var name = MutableStateFlow("")
    var outer = MutableStateFlow("")
    var inner = MutableStateFlow("")
    var ci = MutableStateFlow("")
    var tuan = MutableStateFlow("")
    var xiang = MutableStateFlow("")
    var wu = MutableStateFlow("")
}